package com.nuctech.hardwaredriver.gpio_library;

import android_gpio_api.GPIO;

/**
 * Created by 心魂free on 2019/11/12.
 * <p>
 * GPIO管理类，实现对GPIO的设置功能
 */

public class GPIOManager {

    private GPIOManager() {
    }

    private static class SingletonHolder {

        private static final GPIOManager INSTANCE = new GPIOManager();
    }

    public static GPIOManager getInstance() {

        return SingletonHolder.INSTANCE;
    }

    /**
     * 开启GPIO
     *
     * @param gpio      gpio号
     * @param direction 输入输出模式
     * @return 是否成功
     */
    public boolean open(int gpio, int direction) {

        boolean isSuccess = false;

        int exportGpio = GPIO.exportGpio(gpio);
        if (exportGpio > 0) {

            int setGpioDirection = GPIO.setGpioDirection(gpio, direction);
            if (setGpioDirection > 0) {

                isSuccess = true;
            }
        }

        return isSuccess;
    }

    /**
     * GPIO高低电平状态转换
     *
     * @param gpio  gpio号
     * @param value 状态值
     * @return 是否成功
     */
    public boolean switchStatus(int gpio, int value) {

        int writeGpioStatus = GPIO.writeGpioStatus(gpio, value);
        return writeGpioStatus > 0;
    }

    /**
     * 获取当前GPIO的状态值
     *
     * @param gpio gpio号
     * @return 高低电平值
     */
    public int getGpioCurrentStatus(int gpio) {

        return GPIO.readGpioStatus(gpio);
    }

    /**
     * 关闭GPIO
     *
     * @param gpio gpio号
     * @return 是否成功
     */
    public boolean close(int gpio) {

        int unexportGpio = GPIO.unexportGpio(gpio);
        return unexportGpio > 0;
    }
}
